package com.baomidou.springwind.controller;

import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.entity.*;
import com.baomidou.springwind.mapper.MethodOlogicalDao;
import com.baomidou.springwind.service.UserMethodService;
import com.baomidou.springwind.service.IUserService;
import com.baomidou.springwind.service.MethodOlogicalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.SimpleDateFormat;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import java.text.DateFormat;

/**
 * <p>
 * 文件上传方法论
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/other")
public class MethodOlogicalController extends BaseController {

    @Autowired
    private MethodOlogicalService methodOlogicalService;
    @Autowired
    private MethodOlogicalDao methodOlogicalDao;
    @Autowired
    private UserMethodService userMethodService;
    @Autowired
    private IUserService iUserService;
    /**
     * 文件上传导入--
     */
    @RequestMapping("/methodological/list")
    @Permission("1001")
    public String customList(Model model) {
        return pjaxPath("/file/method_ological_list", model);
    }

    @ResponseBody
    @RequestMapping("/methodological/getData")
    @Permission("1001")
    public String getData(Page<MethodOlogical> page) {
        page = new Page<MethodOlogical>(page.getCurrent(), page.getSize());
        EntityWrapper<MethodOlogical> wrapper = new EntityWrapper<MethodOlogical>();
        wrapper.orderBy("create_time", false);
        page = methodOlogicalService.selectPage(page, wrapper);
        List<MethodOlogical> List = page.getRecords();
        return jsonPage(page);
    }
    @ResponseBody
    @RequestMapping("/methodological/getData1")
    @Permission("1001")
    public String getData1(Page<MethodOlogical> page) {
        page = new Page<MethodOlogical>(page.getCurrent(), page.getSize());
        EntityWrapper<MethodOlogical> wrapper = new EntityWrapper<MethodOlogical>();
        wrapper.orderBy("create_time", false);
        page = methodOlogicalService.selectPage(page, wrapper);
        List<MethodOlogical> List = page.getRecords();
        return jsonPage(page);
    }


    @RequestMapping("/methodological/upload")
    @Permission("1001")
    public String upload(HttpServletRequest request, HttpServletResponse response,Model model)
            throws ServletException, IOException {
        String descripe=request.getParameter("describe");
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            LinkedList linkedList=new LinkedList();
            while(iter.hasNext()) {
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                //  MultipartFile file1 = multiRequest.getFile(iter.next());
                //取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                //    String myFileName1 = file1.getOriginalFilename();
                //如果名称不为“”,说明该文件存在，否则说明该文件不存在

                System.out.println(myFileName);
                //重命名上传后的文件名
                String fileName = file.getOriginalFilename();
                //  String path2 = request.getSession().getServletContext()+"/WEB-INF/static/upload/"+fileName;
                linkedList.add(fileName);
                //定义上传路径
                Date date=new Date();
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd-hh-mm-ss");
                String path = "C:/app/upload/" + sdf.format(date)+fileName;
                linkedList.add(path);
                File localFile = new File(path);
                file.transferTo(localFile);
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
            MethodOlogical methodOlogical = new MethodOlogical();
            methodOlogical.setName(linkedList.get(0).toString());
            methodOlogical.setCreateTime(new Date());
            methodOlogical.setOperatorId(getCurrentUserId());
            methodOlogical.setUrl(linkedList.get(1).toString());
            methodOlogical.setImg(linkedList.get(2).toString());
            methodOlogical.setImgUrl(linkedList.get(3).toString());
            methodOlogical.setDescribe(descripe);
            methodOlogicalService.insert(methodOlogical);


        }
        return pjaxPath("/file/method_ological_list", model);
    }

    @RequestMapping("/methodological/listimage")
    public void getImgae(HttpServletRequest request,
                         HttpServletResponse response) {
        String path =  request.getParameter("file_name").toString();
        response.setContentType("image/jpeg"); // 设置返回内容格式
        File file = new File(path); // 括号里参数为文件图片路径
        if (file.exists()) { // 如果文件存在
            InputStream in;
            try {
                in = new FileInputStream(file);
                OutputStream os = response.getOutputStream(); // 创建输出流
                byte[] b = new byte[1024];
                while (in.read(b) != -1) {
                    os.write(b);
                }
                in.close();
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 城市数据导入--
     */
    @RequestMapping("/methodological/listDown")
    @Permission("1001")
    public String listDown(Model model) {
        return pjaxPath("/file/method_ological_down_list", model);
    }

   /*
   文件下载
    */
    @ResponseBody
    @RequestMapping("/methodological/getDataDown")
    @Permission("1001")
    public String getDataDown(Page<MethodOlogical> page,HttpServletRequest request,
                              HttpServletResponse response) throws Exception{
        String fileName = request.getParameter("file_name");  //下载的文件名（前提：下载的文件需要存放在服务器的位置上，这里是 C:/app/upload/ 中）
        //  fileName= new String((fileName).getBytes(), "iso-8859-1");
        System.out.println("iso-8859-1------------------"+new String((fileName).getBytes(), "iso-8859-1"));
        System.out.println("utf-8------------------"+new String((fileName).getBytes(), "utf-8"));
        byte [] b=fileName.getBytes("ISO-8859-1");
        String str=new String(b,"utf-8");
        System.out.println("第3个------------------"+str);
        String fileUrl =  str;
        downloadFile(request, response, fileName,fileUrl);
        return jsonPage(page);
    }

    @ResponseBody
    @RequestMapping("/methodological/delData")
    @Permission("1001")
    public String delData(Page<MethodOlogical> page,HttpServletRequest request,
                          HttpServletResponse response) throws Exception{
        String id = request.getParameter("id");
        MethodOlogical methodOlogical=methodOlogicalService.selectById(id);
        methodOlogicalService.deleteById(id);
        deleteMethod(methodOlogical.getUrl());
        deleteMethod(methodOlogical.getImgUrl());
        return jsonPage(page);
    }
    public void deleteMethod(String path){
        try{
            File file=new File(path);
            file.delete();
        }catch (Exception e){
            System.out.println("删除文件失败");
        }
    }

    //下载模版工具类
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response,String fileName,String fileUrl) throws Exception {
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {

            // fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            fileUrl= fileName;
            //fileUrl=new String(fileUrl.getBytes("iso-8859-1"), "utf-8");

            response.setHeader("Content-disposition", "attachment; filename="
                    + new String((fileName).getBytes(), "iso-8859-1"));
            // 通知客户文件的MIME类型：
            bis = new java.io.BufferedInputStream(new java.io.FileInputStream(
                    (fileUrl)));
            bos = new java.io.BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            int i = 0;

            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                i++;
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bis = null;
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bos = null;
            }
        }

        UserMethod userMethod= new UserMethod();
        userMethod.setLastTime(new Date());
        userMethod.setName(fileName.substring(31));
        userMethod.setUserId(getCurrentUserId());
        User user=iUserService.selectById(getCurrentUserId());
        userMethod.setLoginName(user.getLoginName());
        userMethodService.insert(userMethod);
    }
}

